<?php
class MatchModel extends BaseModel
{
	const LIST_KEY = 'matchlist';
	const INFO_KEY = 'match';
	const ACTUAL_KEY='actual';
	private $uid	= null;
	public function __construct($uid = null)
	{	
		$this->uid = $uid;
		$this->redis = RedisDB::factory('match');

	}
	public function save($data)
	{
		$this->redis->hMSet(self::INFO_KEY . $this->uid, $data);
	}
	public function actualsave($roomid,$data){
		$this->redis->hMSet(self::ACTUAL_KEY . $roomid, $data);
	}
	public function delete(){
		$this->redis->del(self::INFO_KEY . $this->uid);
	}
	public function getMacth(){
		$matchInfo = $this->redis->hGetAll(self::INFO_KEY . $this->uid);
		return $matchInfo;
	}
	public function getall($roomid){
		$matchInfo = $this->redis->hGetAll(self::ACTUAL_KEY . $roomid);
		return $matchInfo;
	}
	public function saveActual($room,$player){
		if(!$room) return false;
		$matchInfo = $this->redis->hGetAll(self::ACTUAL_KEY . $roomid['id']);
		if(is_array($matchInfo)&&$matchInfo){
			$actualdata[]=$matchInfo;
			foreach($player as $next){
				$actualdata[] =array(
						$next['uid']=>array(
							'score'=>$next['score'],
							'nickname'=>$next['nickname'],
						),
					);
				
				
			}
		}
		$this->actualsave($roomid['id'],$actualdata);
	} 

	public function saveUserMatch($room,$player){
		if(!$room) return false;
		$matchInfo = $this->redis->hGetAll(self::INFO_KEY . $this->uid);
		$match_id=1;
		if(is_array($matchInfo)&&$matchInfo){
			$allmatchlist = $matchInfo['list'];
			$object = json_decode($allmatchlist);
			$org_arr =$object;
			$lastInfo =array_pop($object);
			$l_match_id =$lastInfo->match;
			$match_id =$l_match_id+1;
		}
		$redis_match =json_decode($allmatchlist,true);
		$watcher =array();
		if(isset($watcher)&&$watcher){
			$arr =json_decode($watcher,true);
			foreach($arr as $uid=>$users){
				$watcher[]=$uid;
			}

		}
		$current_score =0;
		foreach($player as $next){
			if($next['uid']==$this->uid){
				$current_score =$next['score'];
				break;
			}
		}
		$append_arr =array(
				'roomid'=>$room['id'],
				'match'=>$match_id,
				'game_type'=>$room['game_type'],
				'time_way'=>$room['time_way'],
				'time_value'=>$room['time_value'],
				'score'=>$current_score,
				'detail'=>array(
						'roomid'=>$room['id'],
						'owner'=>$room['owner'],
						'created'=>$room['time'],
						'player'=>$player,
						'watcher'=>$watcher,
					),
			);
		$redis_match[]=$append_arr;
		//print_r($redis_match);
		//save
		$match_data_arr['list']=json_encode($redis_match);
		$this->save($match_data_arr);
	}


}